import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:ble_measure_plugin/connect_devices_utils.dart';
import 'package:ls_work/a_elder/page/bed_change_history_page.dart';
import 'package:ls_work/a_elder/page/elder_info_page.dart';
// import 'package:flutter_baidutts/flutter_baidutts.dart';
import 'package:ls_work/a_yyt/models/ge_tui_entity.dart';
import 'package:ls_work/a_yyt/models/policy_warning_entity.dart';
import 'package:ls_work/a_yyt/widget/home_hello_cell.dart';
import 'package:ls_work/a_yyt/widget/home_my_work_view.dart';
import 'package:ls_work/a_yyt/widget/policy_cell.dart';
import 'package:ls_work/common/common.dart';
import 'package:ls_work/net/HttpUtil.dart';
import 'package:ls_work/net/net.dart';
import 'package:ls_work/net/post_request.dart';
import 'package:ls_work/res/colors.dart';
import 'package:ls_work/res/gaps.dart';
import 'package:ls_work/res/styles.dart';
import 'package:ls_work/routers/fluro_navigator.dart';
import 'package:ls_work/update_app_utils/app_update_utils.dart';
import 'package:ls_work/update_app_utils/update_dialog.dart';
import 'dart:io';
import 'dart:async';
// import 'package:getuiflut/getuiflut.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:ls_work/util/app_navigator.dart';
import 'package:ls_work/util/speak_text_service.dart';
import 'package:ls_work/util/utils.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage>
    with AutomaticKeepAliveClientMixin {
  // String _platformVersion = 'Unknown';
  // String _payloadInfo = 'Null';
  // String _notificationState = "";
  // String _getClientId = "";
  // String _getDeviceToken = "";
  // String _getVoipToken = "";
  // String _onReceivePayload = "";
  // String _onReceiveNotificationResponse = "";
  // String _onAppLinkPayLoad = "";
  // String _onReceiveVoipPayLoad;

  double volume = 1.0;
  double pitch = 1.0;
  double rate = 1.0;
  // String _newVoiceText;

  @override
  bool get wantKeepAlive => true;

  AppUpdateUtil? utils;

  @override
  void initState() {
    super.initState();
    ConnectDeviceUtils.initMeasureDevice();
    if (Platform.isAndroid) {
      utils = new AppUpdateUtil();
      new Timer(const Duration(milliseconds: 1000), () {
        utils?.getVersion().then((value) {
          if (value != null) {
            _showUpdateDialog(value);
          }
        });
      });
    }
    // initPlatformState();
  }

  @override
  void dispose(){
    super.dispose();
    ConnectDeviceUtils.release();

  }

  // Platform messages are asynchronous, so we initialize in an async method.
  // Future<void> initPlatformState() async {
  //   String platformVersion;
  //   // String payloadInfo = "default";
  //   // String notificationState = "default";
  //   // Platform messages may fail, so we use a try/catch PlatformException.
  //   Getuiflut.initGetuiSdk;
  //
  //   try {
  //     platformVersion = await Getuiflut.platformVersion;
  //     print('platformVersion' + platformVersion);
  //   } on PlatformException {
  //     platformVersion = 'Failed to get platform version.';
  //   }
  //
  //   // If the widget was removed from the tree while the asynchronous platform
  //   // message was in flight, we want to discard the reply rather than calling
  //   // setState to update our non-existent appearance.
  //   if (!mounted) return;
  //
  //   FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
  //       new FlutterLocalNotificationsPlugin();
  //
  //   // initialise the plugin. app_icon needs to be a added as a drawable resource to the Android head project
  //   var initializationSettingsAndroid =
  //       new AndroidInitializationSettings('push');
  //
  //   // var initializationSettingsIOS =
  //   //     IOSInitializationSettings(onDidReceiveLocalNotification: null);
  //
  //   var initializationSettings = InitializationSettings(
  //       android:initializationSettingsAndroid, iOS:IOSInitializationSettings());
  //
  //   flutterLocalNotificationsPlugin.initialize(initializationSettings,
  //       onSelectNotification: onSelectNotification);
  //
  //   Getuiflut().addEventHandler(
  //     onReceiveClientId: (String message) async {
  //       print("flutter onReceiveClientId: $message");
  //       if (!TextUtil.isEmpty(message)) {
  //         _bindGeTuiClientId(message);
  //         SpUtil.putString(Constant.clientId, message);
  //       }
  //     },
  //     onReceiveMessageData: (Map<String, dynamic> msg) async {
  //       // print("flutter onReceiveMessageData: $msg");
  //       // Toast.show('消息来了');
  //       ///透传
  //       // setState(() async {
  //       ///语音合成
  //       //await FlutterBaidutts.instance.speak('A1001，王五，请到外科第一诊室就诊' * 10);
  //
  //       GeTuiInfo info = GeTuiInfo.fromJson(jsonDecode(msg['payload']));
  //       print('id = ${info.id}');
  //       SpeakTextService.addVoice(msg['payload']);
  //       var iOSPlatformChannelSpecifics =
  //           IOSNotificationDetails(presentAlert: true, presentBadge: true);
  //       var androidPlatformChannelSpecifics = AndroidNotificationDetails(
  //         're34dc',
  //         'efgf',
  //         channelDescription: 'erfd',
  //         importance: Importance.max,
  //         priority: Priority.high,
  //         ticker: '智慧养老院',
  //       );
  //       var platformChannelSpecifics = NotificationDetails(
  //         android:androidPlatformChannelSpecifics,
  //         iOS:iOSPlatformChannelSpecifics,
  //       );
  //       await flutterLocalNotificationsPlugin.show(
  //         0,
  //         '智慧养老院',
  //         info.msgBody,
  //         platformChannelSpecifics,
  //         payload: info.msgBody,
  //       );
  //
  //       if (info.bizType == 1201) {
  //         print('1🍎' * 10);
  //         print(jsonDecode(msg['payload']));
  //         Map _map = jsonDecode(msg['payload']);
  //         print('0000🍎' * 10);
  //         print(_map);
  //         print('3333🍎' * 10);
  //         print(_map['params']);
  //         print('4444🍎' * 10);
  //         PolicyWarningInfo _info = PolicyWarningInfo.fromJson(_map['params']);
  //         print('2🍎' * 10);
  //         if (_info != null) {
  //           //报警提醒
  //           showDialog(
  //             context: context,
  //             barrierDismissible: true,
  //             builder: (context) {
  //               return UnconstrainedBox(
  //                 constrainedAxis: Axis.horizontal,
  //                 child: SizedBox(
  //                   width: ScreenUtil.getScreenW(context),
  //                   child: AlertDialog(
  //                     content: PolicyCell(
  //                       type: 0,
  //                       callBack: () {
  //                         Navigator.of(context).pop();
  //                       },
  //                       info: _info,
  //                     ),
  //                   ),
  //                 ),
  //               );
  //             },
  //           );
  //         }
  //       }
  //       // });
  //     },
  //     onNotificationMessageArrived: (Map<String, dynamic> msg) async {
  //       ///消息推送
  //       print("flutter onNotificationMessageArrived");
  //       // setState(() {
  //       //   _notificationState = 'Arrived';
  //       // });
  //     },
  //     onNotificationMessageClicked: (Map<String, dynamic> msg) async {
  //       print("flutter onNotificationMessageClicked");
  //       // setState(() {
  //       //   _notificationState = 'Clicked';
  //       // });
  //     },
  //     onRegisterDeviceToken: (String message) async {
  //       // setState(() {
  //       //   _getDeviceToken = "$message";
  //       // });
  //     },
  //     onReceivePayload: (Map<String, dynamic> message) async {
  //       print("flutter onReceivePayload: $message");
  //       // setState(() {
  //       //   _onReceivePayload = "$message";
  //       // });
  //     },
  //     onReceiveNotificationResponse: (Map<String, dynamic> message) async {
  //       print("flutter onReceiveNotificationResponse: $message");
  //       // setState(() {
  //       //   _onReceiveNotificationResponse = "$message";
  //       // });
  //     },
  //   );
  // }

  Future onSelectNotification(String payload) async {
    if (payload != null) {
      debugPrint('notification payload1: ' + payload);
    }
    // await Navigator.push(context, new MaterialPageRoute(builder: (context) => new SecondScreen(payload)));
  }

  void _showUpdateDialog(Map netMap,{bool force = false}) {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (_) => UpdateDialog(netMap: netMap,force: force,),
    );
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      appBar: AppBar(
        title: Text('"浙里养"一床一码'),
        elevation: 0.5,
        actions: [
          IconButton(
              onPressed: () async {
                var result = await Utils.scan();

                showModalBottomSheet(
                    context: context,
                    backgroundColor: Colors.transparent,
                    builder: (context) {
                      return Container(
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Container(
                              height: 20,
                            ),
                            Text('请选择'),
                            Container(
                              height: 10,
                            ),
                            Gaps.line,
                            TextButton(
                              onPressed: () {
                                Navigator.pop(context);
                                AppNavigator.push(
                                  context,
                                  ElderInfoPage(
                                    customerId: 6546,
                                  ),
                                );
                              },
                              child: Text('查询老人信息'),
                              style: ButtonStyle(
                                  minimumSize: WidgetStateProperty.all(Size(
                                      MediaQuery.of(context).size.width, 40))),
                            ),
                            Gaps.line,
                            TextButton(
                                onPressed: () {
                                  Navigator.pop(context);
                                  AppNavigator.push(
                                    context,
                                    BedChangeHistoryPage("1"),
                                  );
                                },
                                child: Text('查询入住记录'),
                                style: ButtonStyle(
                                    minimumSize: WidgetStateProperty.all(Size(
                                        MediaQuery.of(context).size.width, 40)))),
                            Container(
                              height: 10,
                              color: Colors.grey,
                            ),
                            TextButton(
                                onPressed: () {
                                  Navigator.pop(context);
                                },
                                child: Text(
                                  '取消',
                                  style: TextStyle(color: Colors.black),
                                ),
                                style: ButtonStyle(
                                    minimumSize: WidgetStateProperty.all(Size(
                                        MediaQuery.of(context).size.width, 40)))),
                          ],
                        ),
                        decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.only(
                                topLeft: Radius.circular(16),
                                topRight: Radius.circular(16))),
                      );
                    },
                    isScrollControlled: true);
              },
              icon: Icon(Icons.qr_code_scanner))
        ],
        // actions: [
        //   IconButton(
        //     icon: Icon(
        //       Icons.qr_code_scanner,
        //       size: 30,
        //       color: Colours.app_main,
        //     ),
        //     onPressed: () async {
        //       final code = await Utils.scan();
        //       if (code != null) {
        //         print(code);
        //         NavigatorUtils.goWebViewPage(context, "扫码登录", code.rawContent);
        //       }
        //     },
        //   ),
        // ],
      ),
      body: ListView.builder(
        itemCount: 7,
        itemBuilder: (_, int index) {
          switch (index) {
            case 0:
              return HomeHelloCell();
              break;
            // case 0:
            //   return Container(
            //     padding: EdgeInsets.all(12),
            //     child: LoadAssetImage(
            //       'home/banner_1',
            //       width: ScreenUtil.getScreenW(context),
            //       fit: BoxFit.cover,
            //     ),
            //   ); //HomeSwiperCell();
            //   break;
            case 1:
              return _titleItem('我的工作');
              break;
            case 2:
              return MyWorkView(type: 0);
              break;
            // case 3:
            //   return MyWorkView(type: 1);
            //   break;
            case 4:
              return _titleItem('信息查询');
              break;
            case 5:
              return MyWorkView(type: 2);
              break;
            // case 6:
            //   return MyWorkView(type: 3);
            //   break;
            default:
              return Container();
          }
        },
      ),
    );
  }

  Widget _titleItem(String title) {
    return Padding(
      padding: EdgeInsets.all(15),
      child: Text(
        title,
        style: TextStyles.textBoldDark18,
      ),
    );
  }

  void _bindGeTuiClientId(String clientId) {
    var map = {'cid': clientId};
    HttpUtil.instance
        .getDio()
        .post(HttpApi.geTuiClientIdBind, data: map,options: PostRequest.urlencodedHeader)
        .then((r) {
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {}
      } else {}
    }).catchError((e) {
      print(e.toString());
    });
  }
}
